// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System;
using System.Collections.Generic;
using System.Reflection;
using ValidationAspects.Core;

namespace ValidationAspects.Sdk.Interception
{
	public static class GetInterceptionValidationProperties
	{
		public static IEnumerable<PropertyInfo> ForType(Type type, bool attributedPropertiesOnly)
		{
			Enforce.IsNotNull(type, "type");

			foreach (PropertyInfo propertyInfo in type.GetAllProperties())
			{
				// check validators have not been defined on non setter properties
				if (!propertyInfo.CanValidate())
				{
					if (propertyInfo.IsDefined(typeof(ValidatorAttribute), true))
						throw new ValidationException(string.Format("Validation cannot be applied to property [name:{0}] [type:{1}]. Property does not define a set method.", propertyInfo.Name,
						                                            propertyInfo.DeclaringType));

					continue;
				}

				// only validate properties decorated with a ValidatorAttribute
				if (attributedPropertiesOnly && !propertyInfo.IsDefined(typeof(ValidatorAttribute), true))
					continue;

				yield return propertyInfo;
			}
		}
	}
}